package cn.shengchao.examstar.pay.utils.pay;

import cn.shengchao.base.utils.SpringContextHolder;
import cn.shengchao.examstar.pay.model.service.fy.FYrequest;
import cn.shengchao.examstar.pay.model.service.fy.FuYouUtil;
import cn.shengchao.examstar.pay.model.service.fy.dto.PaymentDetails;
import cn.shengchao.examstar.pay.model.service.fy.response.FuYouApiResponse;
import cn.shengchao.examstar.pay.utils.config.FyConfig;

import java.math.BigDecimal;
import java.util.Objects;

public class WechatH5Pay extends WechatPayAbstract {
    @Override
    public UIPayResponse<PaymentDetails> createPayOrder(PayContext payContext) throws Exception {
        FYrequest fYrequest = new FYrequest(payContext.getOrderId(), payContext.getBody(), new BigDecimal(payContext.getPrice()));
        fYrequest.setAppid(payContext.getAppid());
        fYrequest.setOpenid(payContext.getOpenId());
        fYrequest.setMchntCd(FyConfig.MCHNT_CD);
        fYrequest.setInsCd(FyConfig.INS_CD);
        fYrequest.setType("JSAPI");
        fYrequest.setNotifyUrl(Objects.requireNonNull(SpringContextHolder.getBean(FyConfig.class)).getNotifyUrl()+ payContext.getOrderId());
        FuYouApiResponse fuYouApiResponse = FuYouUtil.createConfig(fYrequest, FyConfig.INS_PRIVATE_KEY, FyConfig.FY_PUBLIC_KEY);
        return new UIPayResponse<>(fuYouApiResponse.getPaymentDetails(), payContext.getOrderId());
    }

    @Override
    public long queryPayOrder(String orderId) throws Exception {
        FuYouApiResponse fuYouApiResponse = FuYouUtil.queryOrder(orderId, FyConfig.INS_CD, FyConfig.MCHNT_CD, "WECHAT", FyConfig.INS_PRIVATE_KEY, FyConfig.FY_PUBLIC_KEY);
        if (fuYouApiResponse.isSuccess()) {
            if(fuYouApiResponse.getParameter("trans_stat").equals("SUCCESS")) {
                return Long.parseLong(fuYouApiResponse.getParameter("order_amt"));
            }
        }
        return 0;
    }
}
